package com.macro.mall.tiny.modules.oms.service.impl;

import com.macro.mall.tiny.component.wx.WxClient;
import com.macro.mall.tiny.component.wx.entity.bo.WxBO;
import com.macro.mall.tiny.component.wx.entity.bo.WxTransferBO;
import com.macro.mall.tiny.modules.oms.model.OmsMemberBalanceLog;
import com.macro.mall.tiny.modules.oms.model.OmsSettleApply;
import com.macro.mall.tiny.modules.oms.mapper.OmsSettleApplyMapper;
import com.macro.mall.tiny.modules.oms.service.OmsMemberBalanceLogService;
import com.macro.mall.tiny.modules.oms.service.OmsSettleApplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.macro.mall.tiny.modules.ums.model.UmsMember;
import com.macro.mall.tiny.modules.ums.service.UmsMemberCacheService;
import com.macro.mall.tiny.modules.ums.service.UmsMemberService;
import com.macro.mall.tiny.security.util.SpringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * <p>
 * 提现申请表 服务实现类
 * </p>
 *
 * @author tyrone
 * @since 2024-10-31
 */
@Service
public class OmsSettleApplyServiceImpl extends ServiceImpl<OmsSettleApplyMapper, OmsSettleApply> implements OmsSettleApplyService {

    @Autowired
    private WxClient wxClient;

    @Autowired
    private OmsMemberBalanceLogService omsMemberBalanceLogService;

    @Autowired
    private UmsMemberService umsMemberService;

    @Autowired
    private UmsMemberCacheService umsMemberCacheService;

    @Override
    public void handleSettleApply(OmsSettleApply apply) {
        if (apply.getStatus() == 1) {
            // 提现中
            apply.setStatus(3);
            updateById(apply);
            WxBO transfer = wxClient.transfer(apply);
            if (transfer.getSuccess()) {
                // 提现成功
                apply.setHandleTime(new Date());
            } else {
                // 提现失败
                apply.setHandleTime(new Date());
                apply.setStatus(5);
                apply.setErrorMsg(transfer.getErrorMsg());
            }
            updateById(apply);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void handleInnerLogic(WxBO wxBO) {
        WxTransferBO wxTransferBO = wxBO.getWxTransferBO();
        String settleOrderId = wxTransferBO.getOutBatchNo();
        if (!wxBO.getSuccess() || !wxTransferBO.getSuccess()) {
            if (StringUtils.isNotEmpty(settleOrderId)) {
                SpringUtil.getBean(OmsSettleApplyService.class).update()
                        .set("status", 5)
                        .set("error_msg", wxBO.getErrorMsg() == null ? wxTransferBO.getErrorMsg() : wxBO.getErrorMsg())
                        .eq("settle_order_id", settleOrderId).update();
            }
        } else {
            OmsSettleApply apply = SpringUtil.getBean(OmsSettleApplyService.class).query().eq("settle_order_id", settleOrderId).one();
            Integer fee = apply.getFee();
            // 提现成功，扣减用户余额
            UmsMember umsMemberByOpenId = umsMemberService.getUmsMemberByOpenId(apply.getOpenId());
            umsMemberByOpenId.setBalance(umsMemberByOpenId.getBalance() - fee);
            umsMemberService.updateById(umsMemberByOpenId);
            umsMemberCacheService.delMember(umsMemberByOpenId.getId());
            // 记录余额变动日志
            OmsMemberBalanceLog omsMemberBalanceLog = new OmsMemberBalanceLog();
            omsMemberBalanceLog.setFee(fee);
            omsMemberBalanceLog.setBalance(umsMemberByOpenId.getBalance());
            omsMemberBalanceLog.setMemberId(umsMemberByOpenId.getId());
            omsMemberBalanceLog.setCreateTime(new Date());
            omsMemberBalanceLog.setType(1);
            omsMemberBalanceLog.setOpenId(umsMemberByOpenId.getOpenId());
            omsMemberBalanceLog.setDescription(buildDescription(omsMemberBalanceLog));
            omsMemberBalanceLogService.save(omsMemberBalanceLog);
        }
    }

    private String buildDescription(OmsMemberBalanceLog omsMemberBalanceLog) {
        return "用户:" + omsMemberBalanceLog.getOpenId() +
                " 提现到账: " + convertFenToYuan(omsMemberBalanceLog.getFee()) + " 元" + " 当前余额: " + convertFenToYuan(omsMemberBalanceLog.getBalance()) + " 元";
    }

    private String convertFenToYuan(Integer fee) {
        if (fee == null) {
            return "NULL";
        }
        Double v = new Double(fee);
        BigDecimal bigDecimal = new BigDecimal(v).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_HALF_UP);
        return bigDecimal.toString();
    }
}
